package utils

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/pkg/errors"
	"time"
)


type UserToken struct {
	jwt.StandardClaims
	//自定义用户信息
	UserId int `json:"userid"`
}

type AdminToken struct {

}

// 前端用户token过期时间
var FrontUserExpireDuration = time.Hour
var FrontUserSecretKey = []byte("front_user_token")


// 管理端用户token过期时间
var AdminUserExpireDuration = time.Hour * 2
var AdminUserSecretKey = []byte("admin_user_token")

var key = []byte("token")
//生成token
func GenToken(UserId int, expireDuration time.Duration, secrite_key []byte) (string,error) {
	user := UserToken{
		StandardClaims:jwt.StandardClaims{
			//现在+过期时间
			ExpiresAt: time.Now().Add(expireDuration).Unix(),
			Issuer: "yanwei_xuexiao",
		},
		UserId:UserId,
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256,user)
	return token.SignedString(secrite_key)
}
//认证token
func AuthTokne(tokenString string, secreKey []byte)  (*UserToken, error) {
	//解析token
	token, err := jwt.ParseWithClaims(tokenString,&UserToken{}, func(token *jwt.Token) (key interface{}, err error) {
		return secreKey, nil
	})
	if err != nil{
		return nil,err
	}

	clasims,is_ok := token.Claims. (*UserToken)
	//验证token
	if is_ok && token.Valid{
		return clasims, nil
	}
	return nil,errors.New("token valid err")
}
